﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using SF.Code.Extension.StringHelper;

namespace SG.Productivity.DesktopControlPanel.Support
{
    public class StrongNameValueCollection : NameValueCollection, IModifiableParameterCollection
    {
        /// <summary>
        /// This method exists for the C# collection initializer syntax (it's actually duck typing)
        /// </summary>
        /// <typeparam name="TElement"></typeparam>
        /// <param name="item"></param>
        public void Add<TElement>(TElement item)
        {
            Put(item);
        }

        public IModifiableParameterCollection Put<TElement>(TElement item)
        {
            Add(KeyName(typeof(TElement)), item.ToString());
            return this;
        }

        private static string KeyName(Type key)
        {
            return key.Name.FirstToLower();
        }

        public IEnumerable<TElement> Get<TElement>()
        {
            var type = typeof (TElement);

            if (!type.IsEnum)
                throw new Exception(type + " is not an Enum!");

            var value = Get(KeyName(type));
            if (string.IsNullOrEmpty(value))
                yield break;

            var split = value.Split(',');
            foreach (var single in split)
                yield return (TElement) Enum.Parse(type, single, true);
        }

        public TElement? FirstOrDefault<TElement>()
            where TElement : struct
        {
            foreach (var element in Get<TElement>())
                return element;

            return null;
        }

        public bool Contains<TElement>(TElement element) where TElement : struct
        {
            return Get<TElement>().Any(existing => element.Equals(existing));
        }
    }
}
